import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

 
public class PaysonUtil {

	private String URL = "http://api.payson.se/1.0/Pay/?";
	private String email ;
	private String returnUrl ;
	private String cancelUrl = "";
	
	
	private String agentID;
	private String mD5nyckel;



	public PaysonUtil(String email, String returnUrl,
			String cancelUrl, String agentID, String mD5nyckel) {
		super(); 
		this.email = email;
		this.returnUrl = returnUrl;
		this.cancelUrl = cancelUrl;
		this.agentID = agentID;
		this.mD5nyckel = mD5nyckel;
	}



	public String doBuy(String firstName, String lastName, String senderEmail, Order  o ) throws Exception{
		String request = "";
		List<NameValuePair> postParams = new ArrayList<NameValuePair>();
		postParams.add(new BasicNameValuePair("senderEmail", senderEmail));
		postParams.add(new BasicNameValuePair("senderFirstName", firstName));
		postParams.add(new BasicNameValuePair("senderLastName", lastName));
		postParams.add(new BasicNameValuePair("receiverList.receiver(0).email", email)); 
		postParams.add(new BasicNameValuePair("receiverList.receiver(0).amount", o.priceVat));
		postParams.add(new BasicNameValuePair("returnUrl", returnUrl));
		postParams.add(new BasicNameValuePair("cancelUrl", cancelUrl));
		postParams.add(new BasicNameValuePair("localeCode", "EN"));
		
		postParams.add(new BasicNameValuePair("orderItemList.orderItem(0).description", o.desc +" - (" +lastName +", " +firstName +")"));
		postParams.add(new BasicNameValuePair("orderItemList.orderItem(0).quantity", "1"));
		postParams.add(new BasicNameValuePair("orderItemList.orderItem(0).unitPrice", o.priceNoVat));
		postParams.add(new BasicNameValuePair("orderItemList.orderItem(0).taxPercentage", "0.25"));
		postParams.add(new BasicNameValuePair("orderItemList.orderItem(0).sku", "sp" +"-" +o.priceVat));

		
		postParams.add(new BasicNameValuePair("returnUrl", returnUrl));
		postParams.add(new BasicNameValuePair("cancelUrl", cancelUrl));
		postParams.add(new BasicNameValuePair("memo", "Memo")); 
		return doRequest(postParams);
	}
	
	
	
	private String doRequest(List<NameValuePair> postParams) throws Exception{
		HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(new URI(URL));
        httppost.setEntity(new UrlEncodedFormEntity(postParams));

        httppost.setHeader("PAYSON-SECURITY-USERID", agentID);
        httppost.setHeader("PAYSON-SECURITY-PASSWORD", mD5nyckel);
		HttpParams httpParameters = new BasicHttpParams();
		// Set the timeout in milliseconds until a connection is established.
		int timeoutConnection = 3000;
		HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
		// Set the default socket timeout (SO_TIMEOUT) 
		// in milliseconds which is the timeout for waiting for data.
		int timeoutSocket = 5000;
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

	 
	    HttpResponse response = httpclient.execute(httppost);
	    
	    StatusLine statusLine = response.getStatusLine();
	    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
	    	HttpParams params = response.getParams();
	        ByteArrayOutputStream out = new ByteArrayOutputStream();
	        response.getEntity().writeTo(out);
	        out.close();
	        String responseString = out.toString();
	    	String token =null;
	        if(responseString.contains("responseEnvelope.ack")){
	        	String ack = responseString.split("responseEnvelope.ack=")[1].split("&")[0];
	        	if(!ack.equals("SUCCESS")){
	        		throw new RuntimeException("");
	        	}
	        	 token = responseString.split("TOKEN=")[1].split("&")[0];
	        
	        
	        }
	        return token ;
	    } else{
	        response.getEntity().getContent().close();
	        throw new IOException(statusLine.getReasonPhrase());
	    }
		
	}
	
}
